package com.faiz.algorithm;

import java.util.HashMap;
import java.util.Map;

public class BuildTree {
    private final Map<Integer, Integer> indexMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder, int preorderLeft, int preorderRight, int inorderLeft, int inorderRight) {
        if (inorderLeft > inorderRight) return null;

        TreeNode root = new TreeNode(preorder[preorderLeft]);
        // 获取根节点在中序中的位置
        int rootIndex = indexMap.get(preorder[preorderLeft]);

        int leftTreeLength = rootIndex - inorderLeft;

        root.left = buildTree(preorder, inorder, preorderLeft + 1, preorderLeft + leftTreeLength, inorderLeft, rootIndex - 1);
        root.right = buildTree(preorder, inorder, preorderLeft + leftTreeLength + 1, preorderRight, rootIndex + 1, inorderRight);
        return root;
    }


    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // 为了提高查询效率，可以使用map来存储中序遍历节点的位置
        for (int i = 0; i < inorder.length; i++) indexMap.put(inorder[i], i);

        return buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    public static void main(String[] args) {
        int[] preorder = {3, 9, 20, 15, 7};
        int[] inorder = {9, 3, 15, 20, 7};
        BuildTree buildTree = new BuildTree();
        TreeNode root = buildTree.buildTree(preorder, inorder);
        System.out.println("ok");
    }
}
